<?php

/*
	计划任务控制文件
*/
if(!defined('IN_SITE') || !defined('IN_ADMIN')) {
	exit('Access Denied');
}
require_once SITE_ROOT.'include/cache.func.php';
$lang = array(
	'misc_cron_week_day_0' => '日',
	'misc_cron_week_day_1' => '一',
	'misc_cron_week_day_2' => '二',
	'misc_cron_week_day_3' => '三',
	'misc_cron_week_day_4' => '四',
	'misc_cron_week_day_5' => '五',
	'misc_cron_week_day_6' => '六',
	'misc_cron_hour' => '时',
	'misc_cron_day' => '日',
);
$op = in_array($op, array('list', 'add', 'edit', 'editsave', 'del' , 'cron', 'batch')) ? $op : 'list';
switch($op){
	case 'cron':
		if($run){
			$cron = $db->fetch_first("SELECT * FROM {$tablepre}crons WHERE cronid='$run'");
			$cron['minute'] = explode("\t", $cron['minute']);
			if(include_once SITE_ROOT.'include/crons/'.$cron['filename']){
				require_once SITE_ROOT.'./include/cron.func.php';
				cronnextrun($cron);
				showmessage("计划任务成功执行。","admincp.php?action=misc&op=list");
			}
			else{
				showmessage("<font color=\"red\">计划任务文件不存在，操作错误。</font>","admincp.php?action=misc&op=list");
			}
		}elseif($edit){
			$cron = $db->fetch_first("SELECT * FROM {$tablepre}crons WHERE cronid='$edit'");
			if(!$cron) {
				cpmsg('未定义！');
			}
			$cron['filename'] = str_replace(array('..', '/', '\\'), array('', '', ''), $cron['filename']);
			$cronminute = str_replace("\t", ',', $cron['minute']);
			$cron['minute'] = explode("\t", $cron['minute']);
			for($i = 0; $i <= 6; $i++) {
					$weekdayselect .= "<option value=\"$i\" ".($cron['weekday'] == $i ? 'selected' : '').">".$lang['misc_cron_week_day_'.$i]."</option>";
				}

				for($i = 1; $i <= 31; $i++) {
					$dayselect .= "<option value=\"$i\" ".($cron['day'] == $i ? 'selected' : '').">$i $lang[misc_cron_day]</option>";
				}

				for($i = 0; $i <= 23; $i++) {
					$hourselect .= "<option value=\"$i\" ".($cron['hour'] == $i ? 'selected' : '').">$i $lang[misc_cron_hour]</option>";
				}
		}else{
				if(strpos($minutenew, ',') !== FALSE) {
					$minutenew = explode(',', $minutenew);
					foreach($minutenew as $key => $val) {
						$minutenew[$key] = $val = intval($val);
						if($val < 0 || $var > 59) {
							unset($minutenew[$key]);
						}
					}
					$minutenew = array_slice(array_unique($minutenew), 0, 12);
					$minutenew = implode("\t", $minutenew);
				} else {
					$minutenew = intval($minutenew);
					$minutenew = $minutenew >= 0 && $minutenew < 60 ? $minutenew : '';
				}

				if(preg_match("/[\\\\\/\:\*\?\"\<\>\|]+/", $filenamenew)) {
					showmessage('您输入的任务脚本文件名包含非法字符，请返回修改。');
				} elseif(!is_readable(SITE_ROOT.($cronfile = "./include/crons/$filenamenew"))) {
					showmessage("您指定的任务脚本文件($cronfile)不存在或包含语法错误，请返回修改。");
				} elseif($weekdaynew == -1 && $daynew == -1 && $hournew == -1 && $minutenew === '') {
					showmessage('您没有指定计划任务执行的时间或条件，请返回修改。');
				}
				$db->query("UPDATE {$tablepre}crons SET name='$namenew', weekday='$weekdaynew', day='$daynew', hour='$hournew', minute='$minutenew', filename='".trim($filenamenew)."' WHERE cronid='$cronid'");
				showmessage('计划任务成功更新。');
		}
	break;
	case 'batch':
		if($ids = implodeids($delete)) {
				$db->query("DELETE FROM {$tablepre}crons WHERE cronid IN ($ids) AND type='user'");
			}
		if($newname = trim($newname)) {
				$db->query("INSERT INTO {$tablepre}crons (name, type, available, weekday, day, hour, minute, nextrun)
					VALUES ('".s_htmlspecialchars($newname)."', 'user', '0', '-1', '-1', '-1', '', '$timestamp')");
			}
		if($available) {
			$ids=implode(',',$available);
			$db->query("UPDATE {$tablepre}crons SET available=1 WHERE cronid IN($ids)");
			$db->query("UPDATE {$tablepre}crons SET available=0 WHERE cronid NOT IN($ids)");
		}else{
			$db->query("UPDATE {$tablepre}crons SET available=0");
		}
		showmessage("计划任务成功更新。","?action=misc&op=list");
	break;
	default:
		$pagesize = 10;
		$order = " ORDER BY cronid";
		$page = max(intval($page), 1);
		$offset = $pagesize*($page-1);
        $limit = " LIMIT $offset, $pagesize";
        $sql = '';
        $sql .= "SELECT * FROM {$tablepre}crons ";
		$num = $db->num_rows($db->query($sql));
        $sql .= " $order $limit";
		$query = $db->query($sql);
		while($cron = $db->fetch_array($query)){
			$cron['weekday'] == -1 && $cron['day'] == -1 && $cron['hour'] == -1 && $cron['minute'] == '' ? 'disabled' : '';
			if($cron['day'] > 0 && $cron['day'] < 32) {
				$cron['time'] = '每月'.$cron['day'].'日';
			} elseif($cron['weekday'] >= 0 && $cron['weekday'] < 7) {
				switch($cron['weekday']){
					case 0:
						$weekday='日';
					break;
					case 1:
						$weekday='一';
					break;
					case 2:
						$weekday='二';
					break;
					case 3:
						$weekday='三';
					break;
					case 4:
						$weekday='四';
					break;
					case 5:
						$weekday='五';
					break;
					case 6:
						$weekday='六';
					break;
					
				}
				$cron['time'] = '每周'.$weekday;
			} elseif($cron['hour'] >= 0 && $cron['hour'] < 24) {
				$cron['time'] = '每日';
			} else {
				$cron['time'] = '每小时';
			}

			$cron['time'] .= $cron['hour'] >= 0 && $cron['hour'] < 24 ? sprintf('%02d', $cron[hour]).'时' : '';

			if(!in_array($cron['minute'], array(-1, ''))) {
				foreach($cron['minute'] = explode("\t", $cron['minute']) as $k => $v) {
					$cron['minute'][$k] = sprintf('%02d', $v);
				}
				$cron['minute'] = implode(',', $cron['minute']);
				$cron['time'] .= $cron['minute'].'分';
			} else {
				$cron['time'] .= '00'.'分';
			}
			$cron['lastrun'] = $cron['lastrun'] ? s_date($cron['lastrun']) : '<b>N/A</b>';
			$cron['nextcolor'] = $cron['nextrun'] && $cron['nextrun'] < $timestamp ? 'style="color: #ff0000"' : '';
			$cron['nextrun'] = $cron['nextrun'] ? s_date($cron['nextrun']) : '<b>N/A</b>';
			$miscdata[] = $cron;
		}
		$pageurl = multi($num, $pagesize, $page, "admincp.php?action=misc&op=list");
	
}
include admin_tpl('misc');
?>